package com.app.controller;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.app.model.Menu;
import com.app.service.MenuService;
import com.app.util.DataTablesQuery;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

/**
 * 接口分页
 * 
 * @author zwxu
 * @date 2017/4/12
 */
@Component
public class MenuQuery extends DataTablesQuery {
	@Resource
	private MenuService menuService;

	public Map<String, Object> queryPage(Map<String, String> params) {
		Map<String, Object> result = new HashMap<String, Object>();
		String iDisplayStart = params.get("iDisplayStart");
		String iDisplayLength = params.get("iDisplayLength");

		List<Object> paramValues = new ArrayList<Object>();
		String sql = buildQuery(params, paramValues);
		sql = toSortQL(sql, params);
		Integer count = menuService.getCount(toCountSQL(sql));
		sql += " limit " + iDisplayStart + ", " + iDisplayLength;
		List<Menu> apiList = menuService.findAllByPage(sql);

		int sEcho = Integer.parseInt(params.get("sEcho"));
		result.put("sEcho", sEcho + 1);
		result.put("aaData", toRowDatas(apiList));
		result.put("iTotalRecords", count);
		result.put("iTotalDisplayRecords", count);
		return result;
	}

	@Override
	protected String buildQuery(Map<String, String> params, List<Object> paramValues) {
		String name = params.get("name");
		StringBuffer sql = new StringBuffer("select * from auth_menu where 1=1 ");

		if (!StringUtils.isEmpty(name)) {
			sql.append("and name like '%" + name + "%'");
		}

		return sql.toString();
	}

	private Object toRowDatas(List<Menu> list) {
		List<Object[]> rows = new ArrayList<Object[]>();
		for (Menu c : list) {
			Object[] row = new Object[6];

			row[0] = c.getId();
			row[1] = c.getName();
			row[2] = c.getUrl();
			row[3] = c.getpId()==null?"无":menuService.getById(c.getpId()).getName();
			row[4] = c.getId();
			row[5] = c.getId();
			rows.add(row);
		}
		return rows;
	}

}
